package com.wd.mylibrary_square.view.fragment

import android.content.Intent
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import coil.load
import coil.transform.RoundedCornersTransformation
import com.alibaba.android.arouter.facade.annotation.Route
import com.ayvytr.adapter.smart
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayout.OnTabSelectedListener
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader
import com.wd.mylibrary_base.bean.LiveBean
import com.wd.mylibrary_base.base.BaseFragment
import com.wd.mylibrary_base.utils.MyApp
import com.wd.mylibrary_square.R
import com.wd.mylibrary_square.databinding.FragmentSquareBinding
import com.wd.mylibrary_square.view.activity.ConstellationActivity
import com.wd.mylibrary_square.view.activity.SearchActivity
import com.wd.mylibrary_square.view.activity.WatchActivity
import com.wd.mylibrary_square.viewmodel.SquareViewModel


@Route(path = "/Square/Square")
class SquareFragment : BaseFragment<SquareViewModel,FragmentSquareBinding>(R.layout.fragment_square) {
    var page:Int=1

    //直播列表适配器
    var liveListAdapter=smart(mutableListOf<LiveBean.Result>(),R.layout.item_live,{ item, position ->
        findViewById<ImageView>(R.id.img).load(item.liveCoverUrl){
            error(R.mipmap.ic_launcher)
            placeholder(R.mipmap.ic_launcher)
            transformations(RoundedCornersTransformation(20f))
        }

        if(item.liveStatus==1){
            findViewById<TextView>(R.id.type).text=" 直播中"
        }else{
            findViewById<TextView>(R.id.type).text=" 录播"
        }

        findViewById<TextView>(R.id.name).text=item.nickName

        findViewById<TextView>(R.id.content).text=item.liveTitle

    }){}.click { item, position ->
        startActivity(Intent(context, WatchActivity::class.java).apply {
            putExtra("liveId",item.liveId)
            putExtra("liveStatus",item.liveStatus)
            putExtra("liveTitle",item.liveTitle)
            putExtra("headPic",item.headPic)
            putExtra("nickName",item.nickName)
            putExtra("follow",item.follow)
            putExtra("anchorId",item.anchorId)
            putExtra("liveCoverUrl",item.liveCoverUrl)
        })
    }
    override fun initView() {
        var userId = MyApp.sp.getInt("userId",0)

        var title= arrayOf("全部","校园","美食","健身","手游")

        for (name in title){
            dataBinding.tab.addTab(dataBinding.tab.newTab().setText(name))
        }

        viewModel.getLiveData(userId,100,1,8)

        RefreshOrLoad(100)

        dataBinding.xrv.adapter=liveListAdapter
        dataBinding.xrv.layoutManager=GridLayoutManager(context,2)

//        //xRecyclerView滑动监听事件
//        dataBinding.xrv.addOnScrollListener(object : RecyclerView.OnScrollListener() {
//            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
//                super.onScrolled(recyclerView, dx, dy)
//
//                if (dy > 0) { // 向下滑动
//                    flag=true
//                    dataBinding.titleHome.visibility=View.GONE
//                } else if (dy < 0) { // 向上滑动
//                    flag=false
//                }
//            }
//
//            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
//                super.onScrollStateChanged(recyclerView, newState)
//
//                when (newState) {
//                    RecyclerView.SCROLL_STATE_IDLE -> {
//                        // 停止滚动
//                        if(flag){
//                            dataBinding.titleHome.visibility=View.GONE
//                        }else{
//                            dataBinding.titleHome.visibility=View.VISIBLE
//                        }
//                    }
//                    RecyclerView.SCROLL_STATE_DRAGGING -> {
//                        // 用户正在拖动
//                        dataBinding.titleHome.visibility=View.GONE
//                    }
//                    RecyclerView.SCROLL_STATE_SETTLING -> {
//                        // 动能滑动（用户快速滑动后释放）
//
//                    }
//                }
//            }
//        })

        //tab 选择改变事件
        dataBinding.tab.addOnTabSelectedListener(object :OnTabSelectedListener{
            override fun onTabSelected(tab: TabLayout.Tab?) {

                when(tab?.position){
                    0->{
                        liveListAdapter.clear()
                        viewModel.getLiveData(userId,100,1,6)

                        RefreshOrLoad(100)
                    }

                    1->{
                        liveListAdapter.clear()
                        viewModel.getLiveData(userId,101,1,6)

                        RefreshOrLoad(101)
                    }

                    2->{
                        liveListAdapter.clear()
                        viewModel.getLiveData(userId,102,1,6)

                        RefreshOrLoad(102)
                    }

                    3->{
                        liveListAdapter.clear()
                        viewModel.getLiveData(userId,103,1,6)

                        RefreshOrLoad(103)
                    }

                    4->{
                        liveListAdapter.clear()
                        viewModel.getLiveData(userId,104,1,6)

                        RefreshOrLoad(104)
                    }
                }

            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {

            }

            override fun onTabReselected(tab: TabLayout.Tab?) {

            }

        })

        //跳转搜索页面
        dataBinding.search.setOnClickListener{
            startActivity(Intent(context,SearchActivity::class.java))
        }

//        dataBinding.search.setOnFocusChangeListener { view, b ->
//           ARouter.getInstance().build("/Square/Search").navigation()
//        }

        //跳转星座匹配
        dataBinding.Constellation.setOnClickListener({
            startActivity(Intent(context,ConstellationActivity::class.java))
        })

    }

    //封装加载 刷新 方法
    fun RefreshOrLoad(liveType:Int){
        var userId = MyApp.sp.getInt("userId",0)
        //上拉刷新  下拉加载
        dataBinding.srl.setRefreshHeader(ClassicsHeader(context))
        dataBinding.srl.setRefreshFooter(ClassicsFooter(context))

        dataBinding.srl.setOnRefreshListener({
            liveListAdapter.clear()
            page=1
            viewModel.getLiveData(userId,liveType,page,6)
            it.finishRefresh()
        })

        dataBinding.srl.setOnLoadMoreListener({
            page++
            viewModel.getLiveData(userId,liveType,page,6)
            it.finishLoadMore()
        })
    }

    override fun dataObserve() {
        //网络数据赋值
        viewModel.liveData.observe(this,{
            if(it.result!=null){
                liveListAdapter.update(it.result,true)
            }
        })
    }

}





